import React, {
  CSSProperties,
  FC,
  useCallback,
  useEffect,
  useRef,
  useState,
} from 'react';
import classNames from 'classnames';
import { getLeft } from './util';
import './index.less';

const prefixClass = 'abc-slider';

export interface layoutTypeProps {
  className?: string;
  style?: CSSProperties;
  disabled?: boolean;
  onChange?: (value: number) => {};
  range?: any;
}

type refObjType = {
  // 是否按下鼠标
  isDown?: boolean;
  // 按下时的位置
  startIndex?: number;
};

const slider: FC<layoutTypeProps> = props => {
  const [value, setValue] = useState(0);
  const refObj = useRef<refObjType>({}); // 保存一些变量
  const sliderRef = useRef(document.createElement('div'));
  const { disabled, onChange } = props;

  const onMouseMove = useCallback(
    e => {
      if (refObj.current.isDown) {
        console.log('移动');
        let valueTemp =
          value +
          ((e.clientX - (refObj.current.startIndex || 0)) /
            sliderRef.current.offsetWidth) *
            100;
        if (valueTemp > 100) {
          valueTemp = 100;
        } else if (valueTemp < 0) {
          valueTemp = 0;
        } else {
          setValue(valueTemp);
        }
        setValue(valueTemp);
        onChange && onChange(valueTemp);
      }
    },
    [value],
  );

  const onMouseUp = useCallback(
    e => {
      console.log('结束');
      document.removeEventListener('mousemove', onMouseMove);
      document.removeEventListener('mouseup', onMouseUp);
      refObj.current.isDown = false;
    },
    [onMouseMove],
  );

  const onMouseDown = useCallback(
    e => {
      console.log(e.layerX, e.layerY);
      console.log('开始');
      document.addEventListener('mousemove', onMouseMove);
      document.addEventListener('mouseup', onMouseUp);
      refObj.current.isDown = true;
      refObj.current.startIndex = e.clientX;
    },
    [onMouseMove],
  );

  const stepOnMouseDown = (e: any) => {
    // 因为我们的值用的是百分比
    const valueTemp =
      ((e.clientX - getLeft(sliderRef.current)) /
        sliderRef.current.offsetWidth) *
      100;
    setValue(valueTemp);
  };

  return (
    <div
      ref={sliderRef}
      onMouseDown={stepOnMouseDown}
      className={classNames(prefixClass, {
        [`${prefixClass}-disabled`]: disabled,
      })}
      onMouseMove={onMouseMove}
      onMouseUp={onMouseUp}
    >
      <div className={`${prefixClass}-rail`}></div>
      <div
        className={`${prefixClass}-track`}
        style={{ left: '0%', right: 'auto', width: `${value}%` }}
      />
      <div className={`${prefixClass}-step`}></div>
      {/* handle 把手 */}
      <div
        onMouseDown={onMouseDown}
        className={`${prefixClass}-handle`}
        role="slider"
        style={{
          left: `${value}%`,
          right: 'auto',
          transform: 'translateX(-50%)',
        }}
      />
      <div className={`${prefixClass}-mark`}></div>
    </div>
  );
};
export default slider;
